//============================================================================
// Name        : SerialPort.h
// Author      : Casey Kelso
// Copyright   : Kineticsproject.com (c) 2010
// Description : Linux Serial Port Module
// Created	   : September 14th 2010
//============================================================================

#include "SerialPort.h"
#include <fcntl.h>
#include <termios.h>
#include <string.h>
#include <unistd.h>


SerialPort::SerialPort() : SERIAL_NO_DATA_PROCESSED(0), SERIAL_ERROR(65535)
{

}

SerialPort::~SerialPort()
{

}

void SerialPort::Close(void)
{
	close(fileHandle);
}

bool SerialPort::Open(const char* deviceNode)
{

     bool   result = true;
     struct termios tio;
     struct termios stdio;

     memset(&stdio,0,sizeof(stdio));
     stdio.c_iflag=0;
     stdio.c_oflag=0;
     stdio.c_cflag=0;
     stdio.c_lflag=0;
     stdio.c_cc[VMIN]=1;
     stdio.c_cc[VTIME]=0;
     tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
     tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
     fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);       // make the reads non-blocking


     memset(&tio,0,sizeof(tio));
     tio.c_iflag=0;
     tio.c_oflag=0;
     tio.c_cflag=CS8|CREAD|CLOCAL;           // 8n1, see termios.h for more information
     tio.c_lflag=0;
     tio.c_cc[VMIN]=1;
     tio.c_cc[VTIME]=5;

     fileHandle=open(deviceNode, O_RDWR | O_NONBLOCK);
     cfsetospeed(&tio,B19200);            // 19200 baud
     cfsetispeed(&tio,B19200);            // 19200 baud

     tcsetattr(fileHandle,TCSANOW,&tio);

     return(result);

}

uint16_t SerialPort::Read(unsigned char* buffer, uint16_t size)
{
    uint16_t result = SERIAL_NO_DATA_PROCESSED;

    result = read(fileHandle,buffer,size);
    if ((SERIAL_NO_DATA_PROCESSED != result) && (SERIAL_ERROR != result))
    {
    //   write(STDOUT_FILENO,buffer,result);        // if new data is available on the serial port, print it out
    }

    return result;
}


uint16_t SerialPort::Write(const char* buffer, uint16_t size)
{
    uint16_t result = SERIAL_NO_DATA_PROCESSED;

    if (0 < size)
    {
     //   result = write(fileHandle,buffer, size);          // if new data is available on the console, send it to the serial port

    }

    return result;
}

bool SerialPort::Process()
{
	unsigned char c;
	bool result = true;


    if (read(fileHandle,&c,1) > 0)
    {
    	write(STDOUT_FILENO,&c,1);        // if new data is available on the serial port, print it out
    }

    if (read(STDIN_FILENO,&c,1) > 0)
    {
    	write(fileHandle,&c,1);          // if new data is available on the console, send it to the serial port
    	if ('q' == c) // quit the application
    	{
    		result = false;
    	}
    }

    return(result);
}
